package com.gzy.fisherybackend.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzy.fisherybackend.common.BaseResponse;
import com.gzy.fisherybackend.common.ErrorCode;
import com.gzy.fisherybackend.exception.BusinessException;
import com.gzy.fisherybackend.model.dto.UserLoginRequest;
import com.gzy.fisherybackend.model.dto.UserRegisterRequest;
import com.gzy.fisherybackend.model.entity.User;
import com.gzy.fisherybackend.model.vo.LoginUserVO;
import com.gzy.fisherybackend.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写账号密码！");
        }
        String userName = userRegisterRequest.getUserName();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userName, password, checkPassword);
        return BaseResponse.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if(userLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写账号密码！");
        }
        String userAccount = userLoginRequest.getUserName();
        String userPassword = userLoginRequest.getPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return BaseResponse.success(loginUserVO);
    }

    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return BaseResponse.success(userService.getLoginUserVO(loginUser));
    }

    @GetMapping("/info")
    public BaseResponse<User> getUserInfo(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return BaseResponse.success(loginUser);
    }

    @PutMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        
        // 更新用户信息
        loginUser.setUsername(user.getUsername());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            loginUser.setPassword(user.getPassword());
        }
        loginUser.setEmail(user.getEmail());
        loginUser.setContact(user.getContact());
        loginUser.setUserAvatar(user.getUserAvatar());
        loginUser.setLastLoginTime(new Date());
        
        boolean result = userService.updateById(loginUser);
        
        return BaseResponse.success(result);
    }

    /**
     * 获取所有用户（不分页）
     */
    @GetMapping("/list")
    public BaseResponse<List<User>> listUsers() {
        List<User> userList = userService.list();
        return BaseResponse.success(userList);
    }

    /**
     * 添加新用户
     */
    @PostMapping
    public BaseResponse<Long> addUser(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名和密码不能为空");
        }
        // 检查用户名唯一
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Username", user.getUsername());
        if (userService.count(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        // 密码加密
        user.setPassword(userService.getEncryptPassword(user.getPassword()));
        user.setRegisterTime(new Date());
        user.setLastLoginTime(new Date());
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return BaseResponse.success(user.getUserID() != null ? user.getUserID().longValue() : null);
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public BaseResponse<Boolean> updateUserById(@PathVariable Integer id, @RequestBody User user) {
        user.setUserID(id);
        boolean result = userService.updateById(user);
        return BaseResponse.success(result);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable Integer id) {
        boolean result = userService.removeById(id);
        return BaseResponse.success(result);
    }

}

